package com.zhoust.fastdome.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * @author zhoust
 * @Date 2021/9/28 16:01
 * @Desc <TODO DESC>
 */
@Slf4j
public class MyRequestUtils extends HttpServletRequestWrapper {

    private final String body;


    public MyRequestUtils(HttpServletRequest request) throws IOException {
        super(request);
        this.body = getBody(request);
    }

    /**
     * 从 request 中获取请求体
     * @param request
     * @return
     * @throws IOException
     */
    private String getBody(HttpServletRequest request) throws IOException{
        StringBuilder body = new StringBuilder();
        BufferedReader reader = request.getReader();
        String readLine = reader.readLine();
        while (readLine != null){
            body.append(readLine);
            readLine = reader.readLine();
        }
        return body.toString();
    }

    public String getBody() {
        return body;
    }
    @Override
    public ServletInputStream getInputStream()  {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes());
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }
            @Override
            public void setReadListener(ReadListener readListener) {
            }
            @Override
            public int read(){
                return bais.read();
            }
        };
    }
    @Override
    public BufferedReader getReader(){
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}
